﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MyBet.Helpers;
using System.Reflection;
using MyBet.Class;
using MyBet.Web;
using System.ServiceModel.DomainServices.Client;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Collections.Generic;

namespace MyBet
{
	public partial class MainPage : UserControl
	{
        ////private UserRegistrationContext userRegistrationContext = new UserRegistrationContext();
        //private Comments _comments;

        //public Comments Comments
        //{
        //    get { return _comments; }
        //    set { _comments = value; }
        //}

        /// <summary>
        /// Return true if user with "bet" rights is authenticated
        /// </summary>
        public bool IsBetUserAuthenticated
        {
            get { return App.CurrentUser != null; }
        }

		public MainPage()
		{
            DateTime currentDate = DateTime.Now;
			// Required to initialize variables
			InitializeComponent();
            LblCopyright.Text = String.Format("Phoenix Copyright (c) {0}", currentDate.Year);
            // Culture
            Helpers.LangHelper l = new Helpers.LangHelper();
            l.ChangeCulture(Helpers.LangHelper.DefaultCulture);
            UpdateCulture();
            // Subscribe to login/logout event
            UserStatus.OnLogin += new MyBet.UserStatus.Login(UserStatus_OnLogin);
            UserStatus.OnLogout += new MyBet.UserStatus.Logout(UserStatus_OnLogout);
            UserStatus.MainPageParent = this;
            // Subscribe to join contest event
            myContest.JoinContestControl.OnJoinContest+=new JoinContest.JoinContestDelegate(JoinContestControl_OnJoinContest);
            //JoinContestControl.OnJoinContest+=new JoinContest.JoinContestDelegate(JoinContestControl_OnJoinContest);
            // Subscribe to disjoin contest event
            //AccountControl.OnDisjoinContest += new MyAccountControl.DisjoinContestDelegate(AccountControl_OnDisjoinContest);
            // Update tab header display
            UpdateTabDisplay();
            AccountControl.OnCustomContestChanged += new MyAccountControl.CustomContestChangeDelegate(AccountControl_OnCustomContestChanged);
		}

        void AccountControl_OnCustomContestChanged()
        {
            Betcontent.ChampionshipDayBetControl.Update();
            UserStatus.UserInfo.UpdateCulture();
        }

        /// <summary>
        /// Disjoint a contest
        /// </summary>
        void AccountControl_OnDisjoinContest()
        {
            MainTab.SelectedItem = GetDefaultTab();
            UserStatus.User = null;
            App.CurrentUser = null;
            WebContext.Current.Authentication.Logout(false);
            UserStatus.UpdateCulture();
            UserStatus_OnLogout();
            UpdateCulture();
        }

        /// <summary>
        /// Join a contest
        /// </summary>
        void JoinContestControl_OnJoinContest()
        {
            MainTab.SelectedItem = GetDefaultTab();
            UserStatus.User=null;
            App.CurrentUser = null;
            WebContext.Current.Authentication.Logout(false);
            UserStatus.UpdateCulture();
            UserStatus_OnLogout();
            UpdateCulture();
        }

        void UserStatus_OnLogout()
        {
            // Update number of members online
           //App.UserRegistration.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);
            

            SecurityServiceReference.SecurityServiceClient svc = new SecurityServiceReference.SecurityServiceClient();
            svc.GetNumberOfUsersOnlineCompleted+=new EventHandler<SecurityServiceReference.GetNumberOfUsersOnlineCompletedEventArgs>(svc_GetNumberOfUsersOnlineCompleted);
            svc.GetNumberOfUsersOnlineAsync();

            //svc. += new EventHandler<EventServiceReference.GetBestScoreCompletedEventArgs>(svc_GetBestScoreCompleted);
            //svc.GetBestScoreAsync(currentEvent.GetEvent._eventId);

            //userRegistrationContext.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);
            bool b = WebContext.Current.User.IsAuthenticated;
            // update bet content
            Betcontent.ChampionshipDayBetControl.Matchs.Reload();
            // Update tab header display
            UpdateTabDisplay();
            UpdateCulture();
        }

        void svc_GetNumberOfUsersOnlineCompleted(object sender, SecurityServiceReference.GetNumberOfUsersOnlineCompletedEventArgs e)
        {
            try
            {
                if (e.Result != -1)
                {
                    MembersOnline.Text = String.Format(Helpers.LangHelper.GetString("MembersOnline"), e.Result);
                }
                else
                {
                    MembersOnline.Text = String.Format(Helpers.LangHelper.GetString("MemberOnline"), e.Result);
                }
            }
            catch (Exception ex)
            {
                Error errdlg = new Error("",ex.InnerException.ToString(),Error.ErrorType.Info);
                errdlg.Show();
            }
        }

        // TODO : SetCookie dans une classe à part
        private void SetCookie(string key, string value)
        {    
            // Expire in 30 days    
            DateTime expireDate = DateTime.Now + TimeSpan.FromDays(30);     
            string newCookie = key + "=" + value + ";expires=" + expireDate.ToString("R");
            System.Windows.Browser.HtmlPage.Document.SetProperty("cookie", newCookie);
        }


        /// <summary>
        /// Function called when user logs in
        /// </summary>
        void UserStatus_OnLogin()
        {
            // Update number of members online
            //App.UserRegistration.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);
            SecurityServiceReference.SecurityServiceClient svc = new SecurityServiceReference.SecurityServiceClient();
            svc.GetNumberOfUsersOnlineCompleted += new EventHandler<SecurityServiceReference.GetNumberOfUsersOnlineCompletedEventArgs>(svc_GetNumberOfUsersOnlineCompleted);
            svc.GetNumberOfUsersOnlineAsync();

            SetCookie("UserName", App.CurrentUser.UserName);

            myContest.CustomContestCreationControl.CustomContestName.Text = "";
            myContest.CustomContestCreationControl.CustomContestPassword.Password = "";
            myContest.CustomContestCreationControl.CustomContestCode.Text = "";

            //userRegistrationContext.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);
            // Update tab header display
            UpdateTabDisplay();
            // update bet content
            Betcontent.ChampionshipDayBetControl.Update();
            UpdateCulture();
        }

        //private void GetNumberOfUserOnline_Completed(InvokeOperation<int> operation)
        //{
        //    if (!operation.IsCanceled)
        //    {
        //        if (!operation.HasError)
        //        {
        //            if (operation.Value > 1)
        //            {
        //                MembersOnline.Text = String.Format(Helpers.LangHelper.GetString("MembersOnline"), operation.Value);
        //            }
        //            else
        //            {
        //                MembersOnline.Text = String.Format(Helpers.LangHelper.GetString("MemberOnline"), operation.Value);
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// Return default tab in function of user role
        /// </summary>
        /// <returns></returns>
        private TabItem GetDefaultTab()
        {
            if (App.CurrentUser == null)
            {
                return TabHomeHeader;
            }

            if (WebContext.Current.User.IsInRole(MyBet.Class.User.AdministratorRole))
            {
                return TabMyAccountHeader;
            }
            else if (WebContext.Current.User.IsInRole(MyBet.Class.User.BetManagerRole))
            {
                return TabMyAccountHeader;
            }
            else if (WebContext.Current.User.IsInRole(MyBet.Class.User.PlayerRole))
            {
                return TabMyAccountHeader;
            }

            return TabHomeHeader;
        }

        /// <summary>
        /// Update tab display in function of user role
        /// </summary>
        private void UpdateTabDisplay()
        {
            if (App.CurrentUser == null)
            {
                // no user connected
                // only first tab and about is displayed
                TabAbout.Visibility = Visibility.Visible;
                TabBetHeader.Visibility = Visibility.Collapsed;
                TabHomeHeader.Visibility = Visibility.Visible;
                TabRankingHeader.Visibility = Visibility.Collapsed;
                TabJoinHeader.Visibility = Visibility.Collapsed;
                TabMyAccountHeader.Visibility = Visibility.Collapsed;
                TabGeneralAdministration.Visibility = Visibility.Collapsed;
            }
            else
            {
                TabAbout.Visibility = Visibility.Visible;
                TabBetHeader.Visibility = BooleanToVisibilityConverter.Convert(
                    WebContext.Current.User.IsInRole(MyBet.Class.User.AdministratorRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.BetManagerRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.PlayerRole));
                TabHomeHeader.Visibility = BooleanToVisibilityConverter.Convert(
                    WebContext.Current.User.IsInRole(MyBet.Class.User.RegisteredUsersRole));
                TabMyAccountHeader.Visibility = BooleanToVisibilityConverter.Convert(
                    WebContext.Current.User.IsInRole(MyBet.Class.User.AdministratorRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.BetManagerRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.PlayerRole));
                TabRankingHeader.Visibility = BooleanToVisibilityConverter.Convert(
                    WebContext.Current.User.IsInRole(MyBet.Class.User.AdministratorRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.BetManagerRole) ||
                    WebContext.Current.User.IsInRole(MyBet.Class.User.PlayerRole));
                TabJoinHeader.Visibility = Visibility.Visible;
                TabGeneralAdministration.Visibility = BooleanToVisibilityConverter.Convert(
                    WebContext.Current.User.IsInRole(MyBet.Class.User.AdministratorRole));
            }

            MainTab.SelectedItem = GetDefaultTab();
        }

        #region Culture Management

        /// <summary>
        /// Update labels after changing culture
        /// </summary>
        private void UpdateCulture()
        {
            TabBetHeader.Header = LangHelper.GetString("TabBet");
            TabHomeHeader.Header = LangHelper.GetString("TabHome");
            TabRankingHeader.Header = LangHelper.GetString("TabRanking");
            TabAbout.Header = LangHelper.GetString("TabAbout");
            TabJoinHeader.Header = LangHelper.GetString("TabJoin");
            TabMyAccountHeader.Header = LangHelper.GetString("TabMyAccountHeader");
            aboutControl.UpdateCulture();
            homeControl.UpdateCulture();
            UserStatus.UpdateCulture();
            Betcontent.UpdateCulture();
            // Update number of members online
            //App.UserRegistration.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);

            SecurityServiceReference.SecurityServiceClient svc = new SecurityServiceReference.SecurityServiceClient();
            svc.GetNumberOfUsersOnlineCompleted += new EventHandler<SecurityServiceReference.GetNumberOfUsersOnlineCompletedEventArgs>(svc_GetNumberOfUsersOnlineCompleted);
            svc.GetNumberOfUsersOnlineAsync();
            
            //userRegistrationContext.GetNumberOfUsersOnline(this.GetNumberOfUserOnline_Completed, null);
            RankingControl.UpdateCulture();
            AccountControl.UpdateCulture();
            //JoinContestControl.UpdateCulture();
        }

        /// <summary>
        /// Change culture to "fr"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrFlag_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			Helpers.LangHelper l = new Helpers.LangHelper();
            l.ChangeCulture(Helpers.LangHelper.CultureFr);
            UpdateCulture();
        }

        /// <summary>
        /// Change culture to "en"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EnFlag_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			Helpers.LangHelper l = new Helpers.LangHelper();
			l.ChangeCulture(Helpers.LangHelper.CultureEn);
            UpdateCulture();
        }

#endregion

        #region Authentication

        /// <summary>
        /// Confirm disconnect
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dlgConfirm_Closed(object sender, EventArgs e)
        {
            Error cw = (Error)sender;
            if (cw.DialogResult == true)
            {
                UserStatus.User = null;
                // Disconnect button appears
                UserStatus.UpdateCulture();
            }
        }

       #endregion

    }
}